<template>
  <el-container>
    <el-aside width="300px" class="content-left-list">
      <div class="ps-panel nav-left-menu" style="height: 100%">
        <div class="ps-panel-head">
          <i class="ps-panel-head-icon iconfont icon-guanxiwajue"></i>
          <span class="ps-panel-head-title">模型信息</span>
        </div>

        <div class="ps-panel-body">
          <el-tree
            :data="labels"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            :props="{ label: 'label_name' }"
            @node-click="treeNodeClick"
            :highlight-current="true"
            ref="visualTree"
          ></el-tree>
          <!--<el-menu :default-active="nodeTypes[0].node" class="el-menu-vertical">-->
          <!--<el-menu-item v-for="item of nodeTypes" :index="item.node" :key="item.node" @click="init(item.node)">{{item.node_name}}</el-menu-item>-->
          <!--</el-menu>-->
        </div>
      </div>
    </el-aside>
    <el-main>
      <!-- <div id="neo4jd3" class="neo4jd3"></div> -->
      <!--左侧属性列表 start-->
      <div class="height-100" style="position: absolute; z-index: 1200">
        <leftTreeSider
          :attrlist="attrlist"
          ref="leftAttr"
          :leftAttr_status="isAttr"
        ></leftTreeSider>
      </div>
      <!--左侧属性列表 end-->
      <g6-model class="neo4jd3" ref="g6" @TouchWindow="TouchWindow" @changePage="changePage" :paginations="paginations"></g6-model>
    </el-main>
  </el-container>
</template>

<!--<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>-->
<script>
import G6Model from "../../G6Common/G6Model";
import leftTreeSider from "../../G6Common/leftTreeSider";
import $ from "jquery";

export default {
  name: "index",
  components: {
    G6Model,
    leftTreeSider,
  },
  data: function () {
    return {
      labels: [],

      paginations: {
        pageIndex: 1, // 当前位于哪页
        pageSize: 10, // 页显示多少条
        total: 0, // 总数
        layout: "total, prev, pager, next", // 翻页属性
      },

      // 选中的模型Id和labelName
      currModelId: 0,
      currModelLabelName: "",
      //当前模型的属性信息
      currModelProperties: [],

      //当前选中模型的实例列表
      currModelInstances: [],

      //当前选中的实例信息
      currModelInstance: {
        visible: false,
        rules: {
          名称: [{ required: true, message: "名称不能为空" }],
          // dataType: [{required: true, message: '数据类型不能为空'}],
          // createDate: [{required: true, message: '创建时间不能为空'}]
        },
        data: {},
      },
      isAttr:false,
      attrlist:[],//属性表单
    };
  },
  methods: {
    mysleep(time) {
      return new Promise((resolve) => setTimeout(resolve, time));
    },

    treeNodeClick(data) {
      this.currModelId = data.id;
      this.currModelLabelName = data.label_name;
      // console.log("nnnnnnnnnnnnnnnnnn", this.currModelLabelName);

      //获取模型属性信息
      this.$store.dispatch("ajax", {
        url:
          "services/app-zonghe/api/dicLabelProperties?labelId.equals=" +
          this.currModelId +
          "&paged=false",
        method: "get",
        data: {},
        succeed: (res) => {
          // //异步执行 所有方法默认都是异步执行
          // this.mysleep(3000).then(() => {
          //     //code 添加三秒后执行的逻辑
          //     console.log('sleep 30 .............');
          // })

          // //执行函数内部同步执行 外面为异步
          // (async function(sleepFunc) {
          //     console.log('Do some thing, ' + new Date());
          //     await sleepFunc(3000);
          //     console.log('Do other things, ' + new Date());
          // })(this.mysleep);

          // //同步执行
          // await this.mysleep(3000).then(() => {
          //     //code 添加三秒后执行的逻辑
          //     console.log('sleep 30 .............');
          // })

          this.currModelProperties = res;
          console.log("get properties: ", this.currModelProperties);
        },
      });

      this.getModelInstances(1);
    },
  //获取当前选中模型的节点
    getModelInstances(pageIndex) {
      if (pageIndex === undefined) {
        pageIndex = this.paginations.pageIndex;
      } else {
        this.paginations.pageIndex = pageIndex;
      }

      this.$store.dispatch("ajaxEx", {
        // url:
        //     "services/app-zonghe/api/example/cypher/nodes/" +
        //     this.currModelLabelName,
        url:
          "services/app-zonghe/api/example/g6_dataformat/nodes_and_relationships/" +
          this.currModelLabelName +
          "/_search?page=" +
          (pageIndex - 1) +
          "&size=" +
          this.paginations.pageSize,
        method: "post",
        // data: {page: pageIndex - 1, size: this.paginations.pageSize},
        data: {
          node: {
            where: {
              bool_and: [],
            },
          },
          relationship: {
            where: {
              bool_and: [],
            },
          },
        },
        succeed: (res) => {
          console.log("333333333333333333333", res);
          this.currModelInstances = res.data;
          if (res.data.data.length == 0) {
            this.$message.error("暂无节点!");
          }
          if(pageIndex>1){
            this.$refs["g6"].oneexpand(res.data.data);
          }else{
            this.$refs["g6"].loadTreeSub(res.data.data);
          }
          this.paginations.total = parseInt(res.headers["x-total-count"]);
        },
      });
    },
    showOrEdit(row) {
      console.log("show or edit instance ................. ", row);
      this.currModelInstance.visible = true;
      this.currModelInstance.data = this.clone(row);
    },
    delInstance(row) {
      console.log(
        "del instance ................. ",
        row,
        this.currModelLabelName
      );
      // this.delPopoverClose('del_popover_'+row.id);
      this.$store.dispatch("ajax", {
        url:
          "services/app-zonghe/api/example/cypher/nodes/" +
          this.currModelLabelName +
          "/" +
          row.id,
        method: "delete",
        data: {},
        succeed: () => {
          this.getModelInstances();
          this.$message.success("删除成功");
          this.delPopoverClose("del_popover_" + row.id);
        },
      });
    },
    addModelInstance() {
      this.currModelInstance.visible = true;
      this.currModelInstance.data = {
        id: 0,
        labels: [this.currModelLabelName],
      };
    },
    saveModelInstance() {
      this.$refs.currModelInstance.validate((valid) => {
        if (valid) {
          if (this.currModelInstance.data.id === 0) {
            this.$store.dispatch("ajax", {
              url:
                "services/app-zonghe/api/example/cypher/nodes/" +
                this.currModelLabelName,
              method: "post",
              data: this.currModelInstance.data,
              succeed: () => {
                this.getModelInstances();
                this.$message.success("保存成功");
                this.currModelInstance.visible = false;
                this.$refs.currModelInstance.resetFields();
              },
            });
          } else {
            // this.currModelInstance.data['labels'].push('BBB测试模型');
            // console.log('update ....: ', this.currModelInstance.data)
            this.$store.dispatch("ajax", {
              url:
                "services/app-zonghe/api/example/cypher/nodes/" +
                this.currModelLabelName,
              method: "put",
              data: this.currModelInstance.data,
              succeed: () => {
                this.getModelInstances();
                this.$message.success("保存成功");
                this.currModelInstance.visible = false;
                this.$refs.currModelInstance.resetFields();
              },
            });
          }
        }
      });
    },

    delPopoverShow(ref) {
      this.$refs[ref].doShow();
    },
    delPopoverClose(ref) {
      this.$refs[ref].doClose();
    },

    checkType(any) {
      return Object.prototype.toString.call(any).slice(8, -1);
    },
    clone(any) {
      let retType = this.checkType(any);
      if (retType === "Object") {
        // 拷贝对象
        let o = {};
        for (let key in any) {
          o[key] = this.clone(any[key]);
        }
        return o;
      } else if (retType === "Array") {
        // 拷贝数组
        var arr = [];
        for (let i = 0, leng = any.length; i < leng; i++) {
          arr[i] = this.clone(any[i]);
        }
        return arr;
      } else if (retType === "Function") {
        // 拷贝函数
        return new Function("return " + any.toString()).call(this);
      } else if (retType === "Date") {
        // 拷贝日期
        return new Date(any.valueOf());
      } else if (retType === "RegExp") {
        // 拷贝正则
        return new RegExp(any);
      } else if (retType === "Map") {
        // 拷贝Map 集合
        let m = new Map();
        any.forEach((v, k) => {
          m.set(k, this.clone(v));
        });
        return m;
      } else if (retType === "Set") {
        // 拷贝Set 集合
        let s = new Set();
        for (let val of any.values()) {
          s.add(this.clone(val));
        }
        return s;
      }
      return any;
    },

    initLabels() {
      this.$store.dispatch("ajax", {
        url: "services/app-zonghe/api/dicLabel/tree",
        method: "get",
        succeed: (res) => {
          // console.log(res);
          this.labels = res;
          this.currModelLabelName = res[0].type;
          // console.log(this.$refs.visualTree);
          // setTimeout(() => {
          //   this.$refs.visualTree.setCurrentKey(res[0].id);
          // }, 1000);

          // this.getModelInstances(1);
          //this.init();
        },
      });
    },
    //初始化d3
    init() {
      let _this = this;
      this.$store.dispatch("ajax", {
        url: `services/app-zonghe/api/example/g6_dataformat/nodes_and_relationships/YY学校/_search`,
        method: "post",
        data: {
          node: {
            where: {
              bool_and: [
                {
                  "id.greaterThan": 13104,
                },
                {
                  "id.lessThan": 13145,
                },
              ],
            },
          },
          relationship: {
            where: {
              bool_and: [],
            },
          },
        },
        succeed: (resNeoData) => {
          console.log(resNeoData);
          this.$refs["g6"].loadTreeSub(resNeoData.data);
        },
      });
      // this.$store.dispatch("ajax", {
      //   url:
      //     "services/app-zonghe/api/example/neo4j_dataformat/relationships/YYY联合",
      //   method: "get",
      //   succeed: (resNeoData) => {
      //     var neo4jd3 = new Neo4jD3("#neo4jd3", {
      //       highlight: [
      //         {
      //           class: "Project",
      //           property: "name",
      //           value: "neo4jd3",
      //         },
      //         {
      //           class: "User",
      //           property: "userId",
      //           value: "eisman",
      //         },
      //       ],
      //       icons: {
      //         //                        'Address': 'home',
      //         Api: "gear",
      //         //                        'BirthDate': 'birthday-cake',
      //         Cookie: "paw",
      //         //                        'CreditCard': 'credit-card',
      //         //                        'Device': 'laptop',
      //         Email: "at",
      //         Git: "git",
      //         Github: "github",
      //         Google: "google",
      //         //                        'icons': 'font-awesome',
      //         Ip: "map-marker",
      //         Issues: "exclamation-circle",
      //         Language: "language",
      //         Options: "sliders",
      //         Password: "lock",
      //         Phone: "phone",
      //         Project: "folder-open",
      //         SecurityChallengeAnswer: "commenting",
      //         User: "user",
      //         zoomFit: "arrows-alt",
      //         zoomIn: "search-plus",
      //         zoomOut: "search-minus",
      //       },
      //       images: {
      //         Address: "img/twemoji/1f3e0.svg",
      //         //                        'Api': 'img/twemoji/1f527.svg',
      //         BirthDate: "img/twemoji/1f382.svg",
      //         Cookie: "img/twemoji/1f36a.svg",
      //         CreditCard: "img/twemoji/1f4b3.svg",
      //         Device: "img/twemoji/1f4bb.svg",
      //         Email: "img/twemoji/2709.svg",
      //         Git: "img/twemoji/1f5c3.svg",
      //         Github: "img/twemoji/1f5c4.svg",
      //         icons: "img/twemoji/1f38f.svg",
      //         Ip: "img/twemoji/1f4cd.svg",
      //         Issues: "img/twemoji/1f4a9.svg",
      //         Language: "img/twemoji/1f1f1-1f1f7.svg",
      //         Options: "img/twemoji/2699.svg",
      //         Password: "img/twemoji/1f511.svg",
      //         //                        'Phone': 'img/twemoji/1f4de.svg',
      //         Project: "img/twemoji/2198.svg",
      //         "Project|name|neo4jd3": "img/twemoji/2196.svg",
      //         //                        'SecurityChallengeAnswer': 'img/twemoji/1f4ac.svg',
      //         User: "img/twemoji/1f600.svg",
      //         //                        'zoomFit': 'img/twemoji/2194.svg',
      //         //                        'zoomIn': 'img/twemoji/1f50d.svg',
      //         //                        'zoomOut': 'img/twemoji/1f50e.svg'
      //       },
      //       minCollision: 60,
      //       neo4jData: resNeoData,
      //       nodeRadius: 25,
      //       onNodeDoubleClick: function (node) {
      //         switch (node.id) {
      //           case "25":
      //             // Google
      //             window.open(node.properties.url, "_blank");
      //             break;
      //           default:
      //             console.log(node, "444444444444444444444444444");

      //             _this.$store.dispatch("ajax", {
      //               url:
      //                 "services/app-zonghe/api/example/neo4j_dataformat/relationships/ZZZ联合",
      //               method: "get",
      //               succeed: (res) => {
      //                 console.log("55555555555555555555555555555, res");
      //                 let ggg = neo4jd3.neo4jDataToD3Data(res);
      //                 //去除重复的点和线
      //                 for (var i = 0; i < ggg.nodes.length; i++) {
      //                   //循环LIST
      //                   var temp_node = ggg.nodes[i]; //获取LIST里面的对象
      //                   if (temp_node.id === node.id) {
      //                     ggg.nodes.splice(i, 1);
      //                     i--;
      //                   }
      //                 }
      //                 console.log("ggggggggggggggggg", ggg);
      //                 neo4jd3.updateWithD3Data(ggg);
      //               },
      //             });

      //             postdata = {
      //                 where: {
      //                     bool_and: [
      //                         {
      //                             bool_or: []
      //                         }
      //                     ]
      //                 }
      //             };
      //             $.post('/api/example/neo4j_dataformat/relationships/ZZZ联合/_search',
      //                 {
      //                     username: 'admin',
      //                     password: '123'
      //                 },
      //                 function (fff) {
      //                     console.log("ffffffffffffffffffff", fff)
      //                     ggg = neo4jd3.neo4jDataToD3Data(fff)
      //                     //去除重复的点和线
      //                     for (var i = 0; i < ggg.nodes.length; i++) {  //循环LIST
      //                         var temp_node = ggg.nodes[i];//获取LIST里面的对象
      //                         if (temp_node.id === node.id) {
      //                             ggg.nodes.splice(i, 1)
      //                             i--;
      //                         }
      //                     }
      //                     console.log("ggggggggggggggggg", ggg)
      //                     neo4jd3.updateWithD3Data(ggg);

      //                     // neo4jd3.updateWithNeo4jData(fff);
      //                 },
      //                 "script"
      //             )

      //             break;
      //         }
      //       },
      //       onRelationshipDoubleClick: function (relationship) {
      //         console.log(
      //           "double click on relationship: " + JSON.stringify(relationship)
      //         );
      //       },
      //       zoomFit: false,
      //     });
      //   },
      // });
    },
    //触发打开关闭属性表单
    TouchWindow(isShow,data){
      console.log(isShow,data);
      this.isAttr=isShow;
      if(isShow){
      this.attrlist=data.attrs
      }else{
        this.attrlist=[];
      }

    },
    //下一页
    changePage(type,index){
      let pagenum=index;
      if(type=='next'){
        pagenum=index+1;
      }else{
        pagenum=index-1;
      }
      this.paginations.pageIndex=pagenum;
      this.getModelInstances(pagenum);
    }
  },
  mounted() {
    this.initLabels();
  },
};
</script>
<style lang="less">
.neo4jd3 {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.el-main{
  position: relative;
}
</style>
